package main

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	Uni      *ut.UniversalTranslator //声明一个翻译器
	validate *validator.Validate     //声明一个验证器
)

//多语言翻译验证
func main() {
	r := gin.Default()
	//采用v10新方式验证，创建一个验证器实例
	validate = validator.New()
	//创建两种语言的实例
	zh := zh.New()
	en := en.New()
	//创建一个翻译器，并写入支持的语言
	Uni = ut.New(zh, en)

	//
	r.GET("/multilingual", func(c *gin.Context) {
		locale := c.DefaultQuery("locale", "zh") //将locale语言默认设置为zh
		trans, _ := Uni.GetTranslator(locale)    //获得一个locale语言的翻译器
		//判断是那种语言，默认为zh
		switch locale {
		case "zh":
			//获取到翻译器后就注册到验证器里面
			zh_translations.RegisterDefaultTranslations(validate, trans)
		case "en":
			en_translations.RegisterDefaultTranslations(validate, trans)
		default:
			zh_translations.RegisterDefaultTranslations(validate, trans)
		}
		var person Person
		//开始数据绑定
		if err := c.ShouldBind(&person); err != nil {
			c.JSON(500, gin.H{
				"error": err.Error(),
			})
			c.Abort()
			return
		}
		//绑定完数据开始验证
		if err := validate.Struct(person); err != nil {
			//将err接口类型断言成validator.ValidationErrors验证器的错误集合
			errs := err.(validator.ValidationErrors)
			sliceErrs := []string{}
			for _, e := range errs {
				//将所有错误集合经过翻译后放到切片里
				sliceErrs = append(sliceErrs, e.Translate(trans))
			}
			c.String(500, "%v", sliceErrs) //显示切片错误~
			c.Abort()
			return
		}
		c.JSON(200, gin.H{
			"message": "OK!",
			"person":  person,
		})
	})
	r.Run(":8081")
}

type Person struct {
	Age     int    `form:"age" validate:"required,gt=10"` //用Validate验证器，所用用validate的tag
	Name    string `form:"name" validate:"required"`
	Address string `form:"address" validate:"required"`
}
